package com.nanhang.controller;

import cn.hutool.core.io.FileUtil;

import com.nanhang.common.Result;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;



@RestController
@RequestMapping("/file")
public class FileController {


    //文件的存储目录 E:\BYSJ\DocumentSystem\springboot_file\files
    private static final String ROOT_PATH = System.getProperty("user.dir") + File.separator + "files";
    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws IOException{
        String originalFilename = file.getOriginalFilename();//文件原始名称
        //aaa.png
        String mainName = FileUtil.mainName(originalFilename);//aaa
        String extName = FileUtil.extName("文件的后缀");//png
        if (!FileUtil.exist(ROOT_PATH)){
            FileUtil.mkdir(ROOT_PATH);//如果当前文件的目录不存在，就创建
        }
        //E:\BYSJ\DocumentSystem\springboot_file\1234512_aaa.png
        if (FileUtil.exist(ROOT_PATH + File.separator + originalFilename)){//如果存在了，就重命名一个文件名称
            originalFilename = System.currentTimeMillis() + "_" + mainName + "." + extName;
        }
        File saveFile = new File(ROOT_PATH + File.separator + originalFilename);
        file.transferTo(saveFile);//存储到本地磁盘
        String url = "http://localhost:9000/file/download/" + originalFilename;
        return Result.success(url);//返回文件的链接，这个链接就是文件的下载地址
    }
    @GetMapping("/download/{fileName}")
    public void download(@PathVariable String fileName, HttpServletResponse response) throws IOException {
        String filePath = ROOT_PATH + File.separator + fileName;
        if (FileUtil.exist(filePath)){
            return;
        }
        byte[] bytes = FileUtil.readBytes(filePath);
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(bytes);//文件字节流数组
        outputStream.flush();
        outputStream.close();
    }


}
